<?php
/**
 * [p 页面打印]
 * @param  [type] $arr [description]
 * @return [type]      [description]
 */
function p($arr,$mode=true)
{
	echo '<pre>';
	if(count($arr) <= 1){
		var_dump($arr);
	}else{
		var_export($arr);
	}
	echo '</pre>';
	if( $mode == false)
		die;
}

/**
 * 写日志
 */
function plog($arr,$file='',$request=false)
{
	$logs = '--log-start--'.EOL;
	$logs .= date('Y-m-d H:i:s',time()).EOL ;
	$logs .= "\t FILE  ==> ". $_SERVER['SCRIPT_NAME'].EOL ;
	$logs .= "\t URL   ==> ". $_SERVER['REQUEST_URI'].EOL ;
	$logs .= "\t DATA  ==> ";
	if(is_array($arr)){
		$logs .= 'type:Array: '. json_encode($arr,JSON_UNESCAPED_UNICODE) ;
	}elseif (is_object($arr)) {
		$logs .= 'type:Object: '. json_encode($arr,JSON_UNESCAPED_UNICODE) ;
	}else{
		$logs .= 'type:'.gettype($arr) .': '. $arr ;
	}
	$logs .=  EOL;
	if($request){
		$logs .= 'data_GET : '. json_encode($_GET,JSON_UNESCAPED_UNICODE); 
		$logs .=  EOL;
		$logs .= 'data_POST : '. json_encode($_POST,JSON_UNESCAPED_UNICODE); 
		$logs .=  EOL;
	}
	$logs .= '--log-end--'.EOL;
	$patch = RUN_TMP.'log';
	if(!is_dir($patch) && !mkdir($patch,777,true)){
		die('生成日志文件夹['.$patch.']失败');
	}
	//按期分开日志
	$file = !empty($file) ? $file : 'php_run_'.date('Ymd').'.log';
	if (!file_exists($patch.DS.$file))
		if(!touch($patch.DS.$file)) die('生成日志文件失败');

	if(!file_put_contents($patch.DS.$file, $logs,FILE_APPEND | LOCK_EX ))
		die('写入日志文件失败');
}

//日志写入数据库
function storog($userid,$uname,$msg,$do_time,$lip)
{
	$sql = "insert into ".get_table("admin_log")."(al_userid,al_logname,al_content,al_inserttime,al_ip) values('".$userid."','".$uname."','".$msg."','".$do_time."','".$lip."')";
	$rs = $GLOBALS["conn"]->query($sql);
	if($rs){
		return true;
	}else{
		return false;
	}
}


//返回毫秒的时间
function microtime_float(){
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}

//返回访问者的IP
function return_user_ip(){
	$onlineip="127.0.0.1";
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	return $onlineip;
   /* if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    return $ip;*/
}
//返回随机数码
function randCode($mylen=8)
{
//密码长度:$mylen
	if(empty($mylen)){
		$mylen = 8;
	}
	$array="0123456789";
	$authnum = '';
	for($i=0;$i<$mylen;$i++){
		$authnum .=substr($array,rand(0,9),1);
	}
	return 	$authnum;
}

/**
 * request参数获取【含过滤】
 * @param  [type] $param_name [description]
 * @param  string $convert    [description]
 * @return [type]             [description]
 */
function get_param($param_name,$convert='')
{
	$param_value = "";
	if(isset($_POST[$param_name])){ //优先post
		$param_value = trim($_POST[$param_name]);
	}else if(isset($_GET[$param_name])){
		$param_value = trim($_GET[$param_name]);
	}
	$param_value = RemoveXSS($param_value);
	if(!get_magic_quotes_gpc()){//加上检查数据防sql注入
		$param_value = sql_addslashes($param_value);
	}
	if ('int' == strtolower($convert)){
		if (strlen($param_value)>10)
			$param_value = preg_replace('/[^\d]/is','',$param_value);
		else
			$param_value = (int)$param_value;
	}
	
	return $param_value;
}

function sql_addslashes($value)
{
	if (empty($value)){
		return $value;
	}else{
		return is_array($value) ? array_map('sql_addslashes', $value) : addslashes($value);
	}
}
/**
* @去除XSS（跨站脚本攻击）的函数
* @par $val 字符串参数，可能包含恶意的脚本代码如<script language="javascript">alert("hello world");</script>
* @return  处理后的字符串
* @Recoded By Androidyue
**/
function RemoveXSS($val) {  
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed  
   // this prevents some character re-spacing such as <java\0script>  
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs  
   $val = preg_replace('/([\x00-\x08\x0b-\x0c\x0e-\x19])/', '', $val);  
 
   // straight replacements, the user should never need these since they're normal characters  
   // this prevents like <IMG SRC=@avascript:alert('XSS')>  
   $search = 'abcdefghijklmnopqrstuvwxyz'; 
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';  
   $search .= '1234567890!@#$%^&*()'; 
   $search .= '~`";:?+/={}[]-_|\'\\'; 
   for ($i = 0; $i < strlen($search); $i++) { 
	  // ;? matches the ;, which is optional 
	  // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars 
 
	  // @ @ search for the hex values 
	  $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; 
	  // @ @ 0{0,7} matches '0' zero to seven times  
	  $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; 
   } 
 
   // now the only remaining whitespace attacks are \t, \n, and \r 
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); 
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); 
   $ra = array_merge($ra1, $ra2); 
 
   $found = true; // keep replacing as long as the previous round replaced something 
   while ($found == true) { 
	  $val_before = $val; 
	  for ($i = 0; $i < sizeof($ra); $i++) { 
		 $pattern = '/'; 
		 for ($j = 0; $j < strlen($ra[$i]); $j++) { 
			if ($j > 0) { 
			   $pattern .= '(';  
			   $pattern .= '(&#[xX]0{0,8}([9ab]);)'; 
			   $pattern .= '|';  
			   $pattern .= '|(&#0{0,8}([9|10|13]);)'; 
			   $pattern .= ')*'; 
			} 
			$pattern .= $ra[$i][$j]; 
		 } 
		 $pattern .= '/i';  
		 $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag  
		 $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags  
		 if ($val_before == $val) {  
			// no replacements were made, so exit the loop  
			$found = false;  
		 }  
	  }  
   }  
   return $val;  
}


//设置cookie
function isetcookie($var, $value, $life=0) {
	global $cookiedomain, $cookiepath,$_SERVER;
	if(!empty($life)){
		$life = time() + $life * 86400;
	}
	header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
	if($cookiedomain!=""){
		setcookie($var, $value, $life,$cookiepath,$cookiedomain,$_SERVER['SERVER_PORT']==443?1:0);
	}else{
		setcookie($var, $value, $life,$cookiepath);
	}
}

///////////////////////同步页面类/////////////////////////////
/* *
*	提示并跳转
*
*	$mssage 数据库表名
*	$url 跳转URL
*	$target 跳转方式1，2，3，4
* */
function showinfo($mssage,$url='',$target=2){
	if($target=="1"){
	//只传向，不提示
		echo("<script>location.href='".$url."';</script>");
		exit;
	}
	if($target=="2"){
	//只提示，不传向
		echo("<script>alert('".$mssage."');</script>");
		exit;
	}
	if($target=="3"){
	//提示，并返回上一页
		echo("<script>alert('".$mssage."');".chr(10));
		echo("history.back();</script>");
		exit;
	}
	if($target=="4"){
	//提示并跳转到指定页
		echo("<script>alert('".$mssage."');".chr(10));
		echo("location.href='".$url."';</script>");
		exit;
	}
	if($target=="5"){
	//过2秒钟之后，只传向，不提示
		echo("<script>
		function top_js_goto(){
			location.href='".$url."';
		}
		setTimeout(top_js_goto,2000);
		</script>");
		exit;
	}
	if($target=="6"){
	//过3秒钟之后，传向，提示
		echo("<script>
		function top_js_goto(){
			location.href='".$url."';
		}
		alert('".$mssage."');
		setTimeout(top_js_goto,1000);
		</script>");
		exit;
	}
}


/**
*分页函数
*参数：$num，$perpage,$curr_page,$mpurl,
*说明：总数量,每页条数,当前页号,连接的URL
*
**/
//分页
function multi($num, $perpage, $curr_page, $mpurl) {
	$multipage = '';
	if($num > $perpage) {
		$pages = ceil($num / $perpage);//求总页数
		$multipage .= "<a href=\"$mpurl&page=1\">首页</a>&nbsp<a href=\"$mpurl&page=".(($curr_page>0?$curr_page:1)-1)."\">上一页</a>&nbsp;";
		
		$multipage .= "<a href=\"$mpurl&page=".($curr_page>=$pages?$pages:$curr_page+1)."\">下一页</a>&nbsp<a href=\"$mpurl&page=$pages\" >最后页</a><select name='showpage' id='showpage' onchange='location.href=\"".$mpurl."&page=\"+this.options[this.selectedIndex].value;'>";
		for($i=1;$i<=$pages;$i++){
			if($i==$curr_page){
				$multipage .= '<option value="'.$i.'" selected="selected">'.$i.'/'.$pages.'</option>';
			}else{
				$multipage .= '<option value="'.$i.'">'.$i.'/'.$pages.'</option>';
			}
		}
		$multipage .= "</select>";
	}
	return $multipage;
}

/**
*分页函数
*参数：$num，$perpage,$curr_page,$mpurl,
*说明：总数量,每页条数,当前页号,连接的URL
*
**/
//分页
function multitwo($num, $perpage, $curr_page, $mpurl, $pagenum=3){
	$multipage = '';
	if($num > $perpage) {
		$pages = ceil($num / $perpage);//求总页数
		$multipage .= "<a class='page-prev' href=\"$mpurl&page=".(($curr_page>0?$curr_page:1)-1)."\">上一页</a><span style='width: 20px;'> </span>";
		
		//显示当前页前后5项
		$startpage = $curr_page <= 5 ? 1 : $curr_page-$pagenum;
		$endpage = $pages<=$curr_page+$pagenum ? $pages : $curr_page+$pagenum;
		for($i = $startpage; $i <= $endpage; $i++){
			if($i == $curr_page){
				$multipage .= "<a class='page-cur' href=\"$mpurl&page=$i\">[".$i."]</a>";
			}else{
				$multipage .= "<a href=\"$mpurl&page=$i\">[".$i."]</a>";
			}
		}
		$multipage .= "<a class='page-next' href=\"$mpurl&page=".($curr_page>=$pages?$pages:$curr_page+1)."\">下一页</a>";
	}
	return $multipage;
}

//==================业务end
//判断是否是关联数组
function is_assoc($arr)
{  
    return is_array($arr) && (array_keys($arr) !== range(0, count($arr) - 1));  
}  

// array转化成JSON
function toJson(array $arr)
{
	return json_encode($arr,JSON_UNESCAPED_UNICODE);
}

//api 输出 + die
function op($prm)
{
	die(toJson($prm));
}

/**
 * 筛选信息
 * @param array $data 数据数组
 * @param array $keys 要显示的字段
 * @param bool $isList 是否列表,默认false - 非列表
 * @param bool $isWanna 是否取正,默认true - 正,false - 反
 * @return array
 * @author ljw 20170406
 */
function filterData(array $data=[],array $keys=[], $isList=false, $isWanna=true)
{
	if($isList){
		if($data && $keys){
			foreach($data as $key=>$row){
				foreach($row as $k=>$val){
					if(!in_array($k, $keys) == $isWanna){
						unset($data[$key][$k]);
					}
				}
			}
		}
	}else{
		foreach($data as $key=>$val){
			if(!in_array($key, $keys) == $isWanna){
				unset($data[$key]);
			}
		}
	}
	return $data;
}

/**
 * 二维数组按某键排序
 * @param array $data 数组
 * @param string $col 键名
 * @param int $type 排序方式
 * @return array
 * @author ljw 20170123
 */
function arraySort($data=[],$col='',$type=SORT_DESC)
{
	if(is_array($data)){
		$i=0;
		foreach($data as $k=>$v){
			if(key_exists($col,$v)){
				$arr[$i] = $v[$col];
				$i++;
			}else{
				continue;
			}
		}
	}else{
		return [];
	}
	array_multisort($arr,$type,$data);
	return $data;
}

/*ajax分页函数*/
function getPage($sum ,$url,$curpage = 1,$perpage = 5,$numberpage = 5){
	$totalpage=ceil($sum/$perpage);
	$pevpage=$curpage-1;
	$nextpage=$curpage+1;

	if($curpage > 1){
		$page['fri']= $pevpage;
		$tol2 = $pevpage;
	}else{
		$page['fri']= '1';
		$tol2 = 1;
	}
	if($curpage < $totalpage){
		$page['two']= $nextpage;
		$tol2 = $nextpage-1;
	}else{
		$page['two']= $totalpage;
		$tol2 = $totalpage;
	}
	$page["tol"] .= $tol2.'/'.$totalpage;
	return $page;
}

//==================curl发请求【去哦改版】
function curl_access($url,$send_data=null,$method = 'post')
{
	$ch = curl_init();
	curl_setopt ($ch, CURLOPT_URL, $url); 
	if($method == 'post' && is_array($send_data) && $send_data)
	{
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_POSTFIELDS, $send_data);//添加变量
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	$tmp_sources = curl_exec($ch); 
	curl_close($ch); 
	return $tmp_sources; 
}

